package com.astuetz.autoplay;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.kmshack.newsstand.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用顶部banner图+点指示器(是一个viewPager + PagerSliding实现的)
 * Created by zengxianming on 2017/3/28.
 * version 1.0
 */
public class CommonBannerHolder implements View.OnTouchListener {

    private Context mContext;
    private ViewPager mViewPager;

    private boolean isAttached = false;

    private ViewGroup mViewParent;
    /**
     * 真实数量
     */
    private int mDataSourceSize;

    private Handler mHandler = new Handler();

    /**
     * 自动滚动频率
     */
    private int mSwitchDuration = 5000;

    public boolean isStarted;
    private List<View> mViews;

    private CommonPageAdapter mPagerAdapter;

    private View.OnClickListener mPagerClickListener;
    private PageChangeListener mPageChangeListener;

    /**
     * 不需要设置默认位置
     */
    public static final int NEEDLESS_DEFAULT = -100;

    public CommonBannerHolder(Context cxt) {
        mContext = cxt;
        mViews = new ArrayList<>();
    }

    public boolean isAttached() {
        return isAttached;
    }

    public interface IShowImgAble {
        String getImageUrl();

        /**
         * 高除以宽得到的比例
         */
        float getImgRatio();

        Object getFroward();
    }

    /**
     * @param duration 间隔时间，默认5000ms
     */
    public void setSwitchDuration(int duration) {
        mSwitchDuration = duration;
    }

    public List<View> getViewList() {
        return mViews;
    }

    public void setViews(List<View> views) {
        mViews.clear();
        mViews.addAll(views);
    }

    /**
     * 圆点样式指示器
     * 根据数据自动创建对应ImageView
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public void initHeadBanner(ViewPager vp, List<? extends IShowImgAble> imgUrlList) {
        List<IShowImgAble> bannerBeanList = new ArrayList<>();
        bannerBeanList.addAll(imgUrlList);
        mViews.clear();
        mDataSourceSize = bannerBeanList.size();

        vp.setOnTouchListener(this);

        if(mViewPager != vp) {
            mViewPager = vp;
        }

        ViewGroup.LayoutParams params = mViewPager.getLayoutParams();

        //根据下发的图片宽高算出比例后再计算出对于屏幕宽度而言合适的高度，再设置给ViewPager
        float imgRatio = bannerBeanList.get(mDataSourceSize > 1 ? 1 : 0).getImgRatio();
        if (imgRatio > 0) //url中没有宽高比参数时，按父控件撑起高度
            params.height = (int) (imgRatio * 1080);

        mViewPager.setLayoutParams(params);
        for (IShowImgAble imgBean : bannerBeanList) {
            mViews.add(getImageViewInstance(imgBean));
        }
        mPagerAdapter = new CommonPageAdapter(mViews, mContext, bannerBeanList);
        mViewPager.setAdapter(mPagerAdapter);

        if(mPageChangeListener == null) {
            mPageChangeListener = new PageChangeListener(bannerBeanList.size(), mViewPager);
        }

    }



    private void touchDown() {
        cancelSwitch();
        mDelayRunnable.isRemoved = true;
        mHandler.removeCallbacks(mDelayRunnable);
    }

    private void touchUp() {
        restartSwitch();
    }


    static class SwitchRunnable implements Runnable {
        public volatile boolean isCancel = false;
        public volatile boolean truelyCancel = false;

        Handler handler = new Handler(Looper.getMainLooper());

        private WeakReference<CommonBannerHolder> mBannerHolder;

        public SwitchRunnable(CommonBannerHolder bannarHolder) {
            mBannerHolder = new WeakReference<>(bannarHolder);
        }

        @Override
        public void run() {
            if (isCancel || mBannerHolder == null || mBannerHolder.get() == null || !mBannerHolder.get().isAttached()) {
                truelyCancel = true;
                return;
            }
            truelyCancel = false;
            CommonBannerHolder bannerHolder = mBannerHolder.get();

            bannerHolder.isStarted = true;
            handler.removeCallbacks(this);
            handler.postDelayed(this, bannerHolder.mSwitchDuration);
        }
    }


    private SwitchRunnable mRunnable = new SwitchRunnable(this);

    public void startSwitch() {
        if (getChildCount() > 0 && !isStarted) {
            if (canSwitch()) {
                mHandler.postDelayed(mRunnable, mSwitchDuration);
            }
        }
    }

    private boolean canSwitch() {
        return mDataSourceSize > 1;
    }

    public void restartSwitch() {
        cancelSwitch();
        if (canSwitch()) {
            if (mRunnable.isCancel) {
                if (mRunnable.truelyCancel) {
                    mRunnable.isCancel = false;
                    mHandler.postDelayed(mRunnable, mSwitchDuration);
                } else {
                    mHandler.postDelayed(mRunnable, (int) (mSwitchDuration * 1.5f));
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mRunnable.isCancel = false;
                        }
                    }, mSwitchDuration);
                }
            }

        }
    }

    private int getChildCount() {
        return mDataSourceSize;
    }

    public void cancelSwitch() {
        mHandler.removeCallbacks(mRunnable);
        mRunnable.isCancel = true;
        isStarted = false;
    }

    /**
     * 执行轮播
     *
     * @param index 显示第几页
     */
    public void executeSwitch(int index) {
        index++;
        if (index >= mDataSourceSize + 1 || index < 0) {
            index = mDataSourceSize == 1 ? 0 : 1;//如果只有一张图，只能设置成0，否则下标越界
        }
    }

    /**
     * ViewPager 滑动监听器
     */
    private class PageChangeListener implements ViewPager.OnPageChangeListener {
        int uiPageSize;
        private static final int FIRST_ITEM_INDEX = 1;
        private int mCurrentPagePosition = 0;
        private boolean mIsChanged = false;
        private ViewPager mViewPager;

        PageChangeListener(int dataSize, ViewPager vp) {
            this.uiPageSize = dataSize;
            this.mViewPager = vp;
        }

        public void onPageSelected(int pPosition) {
//            Log.e(getClass().getName(),"p**************************** " + pPosition);

            mIsChanged = true;
            if (uiPageSize > 1) {
                if (pPosition > uiPageSize - 2) {
                    mCurrentPagePosition = FIRST_ITEM_INDEX;
                } else if (pPosition < FIRST_ITEM_INDEX) {
                    mCurrentPagePosition = uiPageSize - 2;
                } else {
                    mCurrentPagePosition = pPosition;
                }
            }

            if (null != mCusPageChangeListener) {
                mCusPageChangeListener.onPageSelected(pPosition);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (ViewPager.SCROLL_STATE_IDLE == state) {//停下时
                if (mIsChanged) {
                    mIsChanged = false;
                }
            }
            if (null != mCusPageChangeListener) {
                mCusPageChangeListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (null != mCusPageChangeListener) {
                mCusPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        }
    }

    //height 服务端会下发
    private View getImageViewInstance(IShowImgAble imgBean) {

        ImageView imageView = new ImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setTag(imgBean);
        imageView.setImageResource(R.drawable.ic_launcher);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setMaxHeight(70);
//        if(imgBean.getImageUrl() != null) {
//            JDImageLoader.getInstance().displayImage(mContext, imgBean.getImageUrl(), imageView,
//                        ToolImage.mExactlySampleOption, DiscoveryBaseTemplet.mLoadingListener);
//        }
        imageView.setOnClickListener(mListener);
        return imageView;
    }

    private View.OnClickListener mListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mPagerClickListener != null) {
                mPagerClickListener.onClick(v);
            }
        }
    };

    /**
     * 用户触摸的时候停止滚动，松开继续滚动
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mDelayRunnable == null) {
            mDelayRunnable = new DelayRunnable();
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                touchDown();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mDelayRunnable.isRemoved = false;
                if (mDelayRunnable.truelyRemoved) {
                    mHandler.postDelayed(mDelayRunnable, mSwitchDuration / 2);
                }
                break;
        }
        return false;
    }

    DelayRunnable mDelayRunnable = null;

    class DelayRunnable implements Runnable {
        public volatile boolean isRemoved = false;

        public volatile boolean truelyRemoved = true;

        @Override
        public void run() {
            if (isRemoved) {
                truelyRemoved = true;
                return;
            }
            touchUp();
        }
    }


    /**
     * 适配器
     *
     * @return
     */
    public PagerAdapter getAdapter() {
        return mPagerAdapter;
    }

    /**
     * 自定义滑动监听器
     *
     * @param mPageChangeListener
     */
    public void setCusPageChangeListener(ViewPager.OnPageChangeListener mPageChangeListener) {
        this.mCusPageChangeListener = mPageChangeListener;
    }

    /**
     * 外部自定义滑动事件
     */
    protected ViewPager.OnPageChangeListener mCusPageChangeListener;
}
